package com.jindy.module.transferMachine.service.impl;

import java.util.List;
import com.jindy.common.utils.DateUtils;
import com.jindy.module.machine.domain.Machine;
import com.jindy.module.machine.mapper.MachineMapper;
import com.jindy.module.product.domain.ProductModel;
import com.jindy.module.product.mapper.ProductModelMapper;
import com.jindy.module.stock.domain.Stock;
import com.jindy.module.stock.mapper.StockMapper;
import com.jindy.module.transfer.domain.SyTransferT;
import com.jindy.module.transfer.domain.TransferApprovedResult;
import com.jindy.module.transfer.mapper.SyTransferTMapper;
import com.jindy.module.transferProduct.domain.SyTransferProductT;
import com.jindy.module.transferProduct.mapper.SyTransferProductTMapper;
import com.jindy.module.warehouse.domain.Warehouse;
import com.jindy.module.warehouse.mapper.WarehouseMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.jindy.module.transferMachine.mapper.SyTransferMachineTMapper;
import com.jindy.module.transferMachine.domain.SyTransferMachineT;
import com.jindy.module.transferMachine.service.ISyTransferMachineTService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.xml.transform.Result;

/**
 * 库存调拨机器记录Service业务层处理
 * 
 * @author jindy
 * @date 2023-04-13
 */
@Service
public class SyTransferMachineTServiceImpl implements ISyTransferMachineTService 
{
    @Resource
    private SyTransferMachineTMapper syTransferMachineTMapper;
    @Resource
    private SyTransferTMapper syTransferTMapper;
    @Resource
    private SyTransferProductTMapper syTransferProductTMapper;
    @Resource
    private StockMapper stockMapper;
    @Resource
    private MachineMapper machineMapper;
    @Resource
    private ProductModelMapper productModelMapper;
    @Resource
    private WarehouseMapper warehouseMapper;

    /**
     * 查询库存调拨机器记录
     * 
     * @param id 库存调拨机器记录主键
     * @return 库存调拨机器记录
     */
    @Override
    public SyTransferMachineT selectSyTransferMachineTById(Long id)
    {
        return syTransferMachineTMapper.selectSyTransferMachineTById(id);
    }

    /**
     * 查询库存调拨机器记录列表
     * 
     * @param syTransferMachineT 库存调拨机器记录
     * @return 库存调拨机器记录
     */
    @Override
    public List<SyTransferMachineT> selectSyTransferMachineTList(SyTransferMachineT syTransferMachineT)
    {
        return syTransferMachineTMapper.selectSyTransferMachineTList(syTransferMachineT);
    }

    /**
     * 新增库存调拨机器记录
     * 
     * @param syTransferMachineT 库存调拨机器记录
     * @return 结果
     */
    @Override
    public int insertSyTransferMachineT(SyTransferMachineT syTransferMachineT)
    {
        syTransferMachineT.setCreateTime(DateUtils.getNowDate());
        return syTransferMachineTMapper.insertSyTransferMachineT(syTransferMachineT);
    }

    /**
     * 扫码新增调拨机器出库，入库记录
     *
     * @param syTransferMachineT 库存调拨机器记录(传参transferId,transferNo,machineNo,transferProperty)
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertSyTransferMachine(SyTransferMachineT syTransferMachineT) {
        int result = 1;
        if (syTransferMachineT != null) {
            //判断是否审批
//            SyTransferT syTransferT = new SyTransferT();
//            syTransferT.setSerialNum(syTransferMachineT.getTransferNo());
//            List<TransferApprovedResult> syTransferApprovedList = syTransferTMapper.selectSyTransferApprovedList(syTransferT);
//            if (!CollectionUtils.isEmpty(syTransferApprovedList)) {
//                TransferApprovedResult result1 = syTransferApprovedList.get(0);
//                if (result1.getBusinessStatus().equals("completed")) {
            //判断出入库
            List<SyTransferMachineT> list = syTransferMachineTMapper.selectSyTransferMachineTList(syTransferMachineT);
            if(!CollectionUtils.isEmpty(list)){//如果记录表中有，就是就是入库
                syTransferMachineT.setTransferProperty("2");
            }else {//如果记录表中此调拨单中没有，就是就是出库库
                syTransferMachineT.setTransferProperty("1");
            }
                    //出库
                    if (syTransferMachineT.getTransferProperty().equals("1")) {
                        Machine machine = new Machine();
                        machine.setMachineNo(syTransferMachineT.getMachineNo());
                        List<Machine> machineList = machineMapper.selectMachineList2(machine);//根据编号查机器信息
                        if(!CollectionUtils.isEmpty(machineList)){
                            Machine machine1 = machineList.get(0);

                            //拿到调拨出库该类型数量
                            SyTransferProductT syTransferProduct = new SyTransferProductT();
                            syTransferProduct.setTransferNo(syTransferMachineT.getTransferNo());
                            syTransferProduct.setModel(machine1.getModel());
                            List<SyTransferProductT> productTList = syTransferProductTMapper.selectSyTransferProductTList(syTransferProduct);
                            if (!CollectionUtils.isEmpty(productTList)){
                                //拿到出库机器表该类型已经出库的数量
                                SyTransferMachineT syTransferMachineT1 = new SyTransferMachineT();
                                syTransferMachineT1.setTransferProperty("1");
                                syTransferMachineT1.setTransferNo(syTransferMachineT.getTransferNo());
                                syTransferMachineT1.setTransferId(syTransferMachineT.getTransferId());
                                syTransferMachineT1.setModel(machine1.getModel());
                                List<SyTransferMachineT> tList = syTransferMachineTMapper.selectSyTransferMachineTList(syTransferMachineT1);
                                if(!CollectionUtils.isEmpty(tList)){
                                    Long sum1 = Long.valueOf(tList.size());//该类型出库机器数量
                                    Long sum2 = productTList.get(0).getQuantity();//该类型需要出库的数量
                                    if(sum1 >= sum2){
                                        throw new RuntimeException("该类型机器已出库完毕，请勿超出数量！");
                                    }
                                }
                                //扫码新增调拨机器出库记录
                                insertOutSyTransferMachine(syTransferMachineT);
                            }else {
                                throw new RuntimeException("调拨单中没有该类型机器！");
                            }
                        }else {
                            throw new RuntimeException("仓库中没有该编号的机器！");
                        }

                    }//入库
                    else if (syTransferMachineT.getTransferProperty().equals("2")) {
                        Machine machine = new Machine();
                        machine.setMachineNo(syTransferMachineT.getMachineNo());
                        List<Machine> machineList = machineMapper.selectMachineList2(machine);//根据编号查机器信息
                        if(!CollectionUtils.isEmpty(machineList)){
                            Machine machine1 = machineList.get(0);

                            //拿到调拨出库该类型数量
                            SyTransferProductT syTransferProduct = new SyTransferProductT();
                            syTransferProduct.setTransferNo(syTransferMachineT.getTransferNo());
                            syTransferProduct.setModel(machine1.getModel());
                            List<SyTransferProductT> productTList = syTransferProductTMapper.selectSyTransferProductTList(syTransferProduct);
                            if (!CollectionUtils.isEmpty(productTList)){
                                //拿到出库机器表该类型已经入库的数量
                                SyTransferMachineT syTransferMachineT1 = new SyTransferMachineT();
                                syTransferMachineT1.setTransferProperty("2");
                                syTransferMachineT1.setTransferNo(syTransferMachineT.getTransferNo());
                                syTransferMachineT1.setTransferId(syTransferMachineT.getTransferId());
                                syTransferMachineT1.setModel(machine1.getModel());
                                List<SyTransferMachineT> tList = syTransferMachineTMapper.selectSyTransferMachineTList(syTransferMachineT1);
                                if(!CollectionUtils.isEmpty(tList)){
                                    Long sum1 = Long.valueOf(tList.size());//该类型已入库机器数量
                                    Long sum2 = productTList.get(0).getQuantity();//该类型需要入库的数量
                                    if(sum1 >= sum2){
                                        throw new RuntimeException("该类型机器已入库完毕，请勿超出数量！");
                                    }
                                }
                                //扫码新增调拨机器入库记录
                                insertInSyTransferMachine(syTransferMachineT);
                            }else {
                                throw new RuntimeException("调拨单中没有该类型机器！");
                            }
                        }else {
                            throw new RuntimeException("仓库中没有该编号的机器！");
                        }
                    }
//                }else {
//                    throw new RuntimeException("此单审批流程未结束，不允许出库");
//                }
//            }
        }
        return result;
    }


    /**
     * 扫码新增调拨机器出库记录
     *
     * @param syTransferMachineT 库存调拨机器记录
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    void insertOutSyTransferMachine(SyTransferMachineT syTransferMachineT){

        try{
            //调拨单
            SyTransferT transfer = syTransferTMapper.selectSyTransferTById(syTransferMachineT.getTransferId());
            //查出机器信息
            Machine machine = new Machine();
            machine.setMachineNo(syTransferMachineT.getMachineNo());
            List<Machine> machineList = machineMapper.selectMachineList2(machine);
            if(!CollectionUtils.isEmpty(machineList)){
                Machine machine1 = machineList.get(0);//这条机器信息
                //放入调拨机器记录表
                syTransferMachineT.setModel(machine1.getModel());
                syTransferMachineT.setProductId(machine1.getProductId());
                syTransferMachineT.setProductName(machine1.getProductName());
                syTransferMachineT.setWarehouseName(machine1.getWarehouseName());
                syTransferMachineT.setMachineSerialNumber(machine1.getMachineSerialNumber());
                syTransferMachineTMapper.insertSyTransferMachineT(syTransferMachineT);

                //修改产品-模型中的数量
                ProductModel productModel = new ProductModel();
                productModel.setDelFlag("0");
                productModel.setProductId(machine1.getProductId().toString());
                productModel.setProductName(machine1.getProductName());
                productModel.setModel(machine1.getModel());
                productModel = productModelMapper.selectProductModel(productModel);

                productModel.setQuantity(productModel.getQuantity()-1);
                productModelMapper.updateProductModel(productModel);

                //修改仓库库存
                Stock stock = new Stock();
                stock.setProductId(machine1.getProductId());
                stock.setModel(machine1.getModel());
                stock.setWarehouseId(machine1.getWarehouseId());
                List<Stock> stocks = stockMapper.selectStockList(stock);
                if(!CollectionUtils.isEmpty(stocks)){
                    stock= stocks.get(0);
                    stock.setQuantity(stock.getQuantity()-1);
                    stock.setAvailableQuantity(stock.getAvailableQuantity()-1);
                    stockMapper.updateStock(stock);
                }

                //拿到调拨单中产品所有数量，判断机器是否出入库完毕
                SyTransferProductT syTransferProduct = new SyTransferProductT();
                syTransferProduct.setTransferNo(syTransferMachineT.getTransferNo());
                List<SyTransferProductT> productTList = syTransferProductTMapper.selectSyTransferProductTList(syTransferProduct);
                if(!CollectionUtils.isEmpty(productTList)){
                    Long pQuantity = productTList.stream().mapToLong(SyTransferProductT::getQuantity).sum();

                    //查出此单所有出库机器
                    SyTransferMachineT syTransferMachineT1 = new SyTransferMachineT();
                    syTransferMachineT1.setTransferProperty("1");
                    syTransferMachineT1.setTransferNo(syTransferMachineT.getTransferNo());
                    syTransferMachineT1.setTransferId(syTransferMachineT.getTransferId());
                    List<SyTransferMachineT> tList = syTransferMachineTMapper.selectSyTransferMachineTList(syTransferMachineT1);
                    if(!CollectionUtils.isEmpty(tList)){
                        Long mQuantity = Long.valueOf(tList.size());//该类型已出库机器数量

                        if(pQuantity > mQuantity){
                            transfer.setEquipmentStatus("1");//出库中
                            syTransferTMapper.updateSyTransferT(transfer);
                        }else if(pQuantity.equals(mQuantity)){
                            transfer.setEquipmentStatus("2");//出库完毕，待入库
                            syTransferTMapper.updateSyTransferT(transfer);
                        }
                    }
                }
            }
        }catch (Exception e) {
            // 处理异常
            throw new RuntimeException("调拨出库扫码失败", e);
        }

    }

    /**
     * 扫码新增调拨机器入库记录
     *
     * @param syTransferMachineT 库存调拨机器记录
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    void insertInSyTransferMachine(SyTransferMachineT syTransferMachineT){
        try {
            //调拨单
//            SyTransferT transferT = new SyTransferT();
//            transferT.setSerialNum(syTransferMachineT.getTransferNo());
//            SyTransferT transfer = syTransferTMapper.selectSyTransferTList(transferT).get(0);
            SyTransferT transfer = syTransferTMapper.selectSyTransferTById(syTransferMachineT.getTransferId());


            //调入仓库的信息
            Warehouse warehouse = new Warehouse();
            warehouse.setWarehouseName(transfer.getInRepertory());
            List<Warehouse> warehouseList = warehouseMapper.selectWarehouseList2(warehouse);
            if(!CollectionUtils.isEmpty(warehouseList)){
                warehouse = warehouseList.get(0);
            }

            //查出机器信息
            Machine machine = new Machine();
            machine.setMachineNo(syTransferMachineT.getMachineNo());
            List<Machine> machineList = machineMapper.selectMachineList2(machine);
            if(!CollectionUtils.isEmpty(machineList)){
                Machine machine1 = machineList.get(0);//这条机器信息
                //放入调拨机器记录表
                syTransferMachineT.setModel(machine1.getModel());
                syTransferMachineT.setProductId(machine1.getProductId());
                syTransferMachineT.setProductName(machine1.getProductName());
                syTransferMachineT.setWarehouseName(transfer.getInRepertory());
                syTransferMachineT.setMachineSerialNumber(machine1.getMachineSerialNumber());
                syTransferMachineTMapper.insertSyTransferMachineT(syTransferMachineT);

                //修改产品-模型中的数量
                ProductModel productModel = new ProductModel();
                productModel.setDelFlag("0");
                productModel.setProductId(machine1.getProductId().toString());
                productModel.setProductName(machine1.getProductName());
                productModel.setModel(machine1.getModel());
                productModel = productModelMapper.selectProductModel(productModel);

                productModel.setQuantity(productModel.getQuantity()+1);
                productModelMapper.updateProductModel(productModel);

                //如果机器所入的仓库有这个类型的机器，则库存数量+1，如果没有，则创建这一类型，其初始数量为0，现存数量为1。
                Stock stock = new Stock();
                stock.setProductId(machine1.getProductId());
                stock.setModel(machine1.getModel());
                stock.setWarehouseId(warehouse.getId());
                List<Stock> stocks = stockMapper.selectStockList(stock);
                if(!CollectionUtils.isEmpty(stocks)){
                    stock= stocks.get(0);
                    stock.setQuantity(stock.getQuantity()+1);
                    stock.setAvailableQuantity(stock.getAvailableQuantity()+1);
                    stockMapper.updateStock(stock);
                }else{
                    Stock stock2 = new Stock();
                    stock2.setProductName(machine1.getProductName());
                    stock2.setProductNo(machine1.getProductNo());
                    stock2.setProductId(machine1.getProductId());
                    stock2.setModel(machine1.getModel());
                    stock2.setQuantity(1L);
                    stock2.setWarehouseId(warehouse.getId());
                    stock2.setWarehouseName(transfer.getInRepertory());
                    stock2.setAvailableQuantity(1L);
                    stock2.setStartQuantity(0L);//本来没有，所以初始数量为0
                    stockMapper.insertStock(stock2);
                }
                //修改机器所属仓库
                machine1.setWarehouseId(warehouse.getId());
                machine1.setWarehouseName(transfer.getInRepertory());
                machineMapper.updateMachine(machine1);

                //拿到调拨单中产品所有数量，判断机器是否出入库完毕
                SyTransferProductT syTransferProduct = new SyTransferProductT();
                syTransferProduct.setTransferNo(syTransferMachineT.getTransferNo());
                List<SyTransferProductT> productTList = syTransferProductTMapper.selectSyTransferProductTList(syTransferProduct);
                if(!CollectionUtils.isEmpty(productTList)){
                    Long pQuantity = productTList.stream().mapToLong(SyTransferProductT::getQuantity).sum();

                    //查出此单所有入库机器
                    SyTransferMachineT syTransferMachineT1 = new SyTransferMachineT();
                    syTransferMachineT1.setTransferProperty("2");
                    syTransferMachineT1.setTransferNo(syTransferMachineT.getTransferNo());
                    syTransferMachineT1.setTransferId(syTransferMachineT.getTransferId());
                    List<SyTransferMachineT> tList = syTransferMachineTMapper.selectSyTransferMachineTList(syTransferMachineT1);
                    if(!CollectionUtils.isEmpty(tList)){
                        Long mQuantity = Long.valueOf(tList.size());//该类型已出库机器数量

                        if(pQuantity > mQuantity){
                            transfer.setEquipmentStatus("3");//入库中
                            syTransferTMapper.updateSyTransferT(transfer);
                        }else if(pQuantity.equals(mQuantity)){
                            transfer.setEquipmentStatus("4");//入库完毕
                            syTransferTMapper.updateSyTransferT(transfer);
                        }
                    }
                }
            }
        } catch (Exception e) {
            // 处理异常
            throw new RuntimeException("调拨入库扫码失败", e);
        }
    }

    /**
     * 修改库存调拨机器记录
     * 
     * @param syTransferMachineT 库存调拨机器记录
     * @return 结果
     */
    @Override
    public int updateSyTransferMachineT(SyTransferMachineT syTransferMachineT)
    {
        syTransferMachineT.setUpdateTime(DateUtils.getNowDate());
        return syTransferMachineTMapper.updateSyTransferMachineT(syTransferMachineT);
    }

    /**
     * 批量删除库存调拨机器记录
     * 
     * @param ids 需要删除的库存调拨机器记录主键
     * @return 结果
     */
    @Override
    public int deleteSyTransferMachineTByIds(Long[] ids)
    {
        return syTransferMachineTMapper.deleteSyTransferMachineTByIds(ids);
    }

    /**
     * 删除库存调拨机器记录信息
     * 
     * @param id 库存调拨机器记录主键
     * @return 结果
     */
    @Override
    public int deleteSyTransferMachineTById(Long id)
    {
        return syTransferMachineTMapper.deleteSyTransferMachineTById(id);
    }
}
